package hanxx.security.handle;

import com.alibaba.fastjson.JSON;
import hanxx.common.utils.*;
import hanxx.common.utils.http.HttpStatus;
import hanxx.security.domain.SysUserLogin;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * edit:韩鑫鑫
 * 部门:产品研发三部
 **/
@Component
public class LogoutSucessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private RedisCache redisCache;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)){
            try {
                Claims claims = JwtUtils.parseJWT(token);
                String uuid = claims.get("login_user_uuid",String.class);
                String redisKey = "login_user_uuid:" + uuid;
                SysUserLogin userLogin = redisCache.getCacheObject(redisKey);
                if (StringUtils.isNotNull(userLogin)){
                    redisCache.deleteObject(redisKey);
                }
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS,"退出成功")));
            } catch (Exception e){

            }
        }
    }
}
